package com.zhongjianjian.jiaoan.jiaoyanjiekoumidengxing.lanjieqi;

import com.zhongjianjian.jiaoan.jiaoyanjiekoumidengxing.zhujie.ForCheck;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;

/**
 * @类名: com.zhongjianjian.jiaoan.lanjieqi
 * @作者: lgt
 * @创建时间: 2020-02-29 19:18
 * @描述:
 **/
@Component
public class ForCheckInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {

        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        ForCheck annotation =  handlerMethod.getMethod().getAnnotation(ForCheck.class);
        if (annotation!=null){
            return chekBiaoShi(request);
        }
        return false;
    }

    public boolean chekBiaoShi(HttpServletRequest request) {
        String check="if redis.call('get',KEYS[1]) then return redis.call('del',KEYS[1]) else return 0 end";
        DefaultRedisScript<Long> defaultRedisScript=new DefaultRedisScript();
        defaultRedisScript.setResultType(Long.class);
        defaultRedisScript.setScriptText(check);//设置Lua脚本
        String key=request.getParameter("token");
        Object execute = redisTemplate.execute(defaultRedisScript, Collections.singletonList(key));
        System.out.println("===redis==="+execute);
        if(execute.toString().equals("1")){
            return true;
        }else{
            return false;
        }
    }
}
